package com.sinaapp.kjWeb.action;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import net.sf.json.JSONObject;
import org.apache.http.Consts;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sinaapp.kjWeb.util.ConfigUtils;



/*
 *auth:徐疆
 *date 2014-1-12 下午4:15:24
 */
public class LoginAction extends Action{
	public static Logger logger=LoggerFactory.getLogger(LoginAction.class);
	private String userID;
	private String passWord;
	
	public LoginAction() {
		super("登录");
	}

	public LoginAction(String userID, String passWord) {
		super("登录");
		this.userID = userID;
		this.passWord = passWord;
	}


	@Override
	public void doAction() {
		HttpPost httpost = new HttpPost("http://218.22.63.5:8082/Home/Login");
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		nvps.add(new BasicNameValuePair("userid",ConfigUtils.getInstance().getValue("kj_userid") ));
		nvps.add(new BasicNameValuePair("password", ConfigUtils.getInstance().getValue("kj_password")));
		httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
		InputStream is=null;
		try {
			CloseableHttpResponse loginResponse = this.getHttpClient().execute(httpost);
			is=loginResponse.getEntity().getContent();
			//检查是否登录成功 
			JSONObject json=getJsonResult(is);
			if(json!=null){
				boolean value=(Boolean) json.get("success");
				if(value){
					logger.debug("登录成功");
					return;
				}
			}
			throw new RuntimeException("登录失败");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("登录出错了",e);
			throw new RuntimeException("登录失败");
		}finally{
			if(is!=null){
				try {
					is.close();
				} catch (IOException e) {
				}
			}
		}
	}

	public String getUserID() {
		return userID;
	}

	public void setUserID(String userID) {
		this.userID = userID;
	}

	public String getPassWord() {
		return passWord;
	}

	public void setPassWord(String passWord) {
		this.passWord = passWord;
	}
	
	
}

